package com.tianjin.weight.model.common;

import com.tianjin.weight.common.CurdWithReturnAdd;
import com.tianjin.weight.entity.Ao;
import com.tianjin.weight.entity.Page;
import com.tianjin.weight.entity.SysRole;
import com.tianjin.weight.exception.BusinessException;
import com.tianjin.weight.exception.code.BaseResponseCode;
import com.tianjin.weight.model.common.base.RoleBase;
import com.tianjin.weight.utils.MapperBeanUtils;
import com.tianjin.weight.vo.req.RoleAddReqVO;

import java.util.Date;

public abstract  class Role<T extends SysRole,R extends RoleAddReqVO,F extends Page> extends RoleBase<T,F> implements CurdWithReturnAdd<T> {
    public T vo;
    public R ro;
    public F fo;
    public Ao ao;

    public Role(T vo, R ro, F fo, Ao ao) {
        this.vo = vo;
        this.ro = ro;
        this.fo = fo;
        this.ao = ao;
    }
    public Long add() throws Exception {
        ao.id = this.addRoleBefore();
        this.addRoleAfter();
        return ao.id;
    }

    public  void update() throws Exception {
        this.updateRoleBefore();
        this.updateRoleAfter();
    }

    public void delete() throws Exception {
        this.deleteRoleBefore();
        this.deleteRoleAfter();
    }

    public void batchDelete() throws Exception{
        this.deleteBatchRoleBefore();
        this.deleteBatchRoleAfter();
    }


    public abstract Long addRoleBefore() throws Exception;
    public abstract void addRoleAfter() throws Exception;

    public void updateRoleBefore() throws Exception {
        SysRole oriSysRole = MapperBeanUtils.getSysRoleMapper().selectByPrimaryKey(ao.id);
        if (null==oriSysRole){
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        SysRole sysRole = SysRole.builder()
                .id(ao.id)
                .name(vo.getName())
                .description(vo.getDescription())
                .status(vo.getStatus())
                .updateTime(new Date())
                .build();
        MapperBeanUtils.getSysRoleMapper().updateByPrimaryKeySelective(sysRole);
        ao.subject = sysRole;
    }
    public abstract void updateRoleAfter() throws Exception;

    public void deleteRoleBefore() throws Exception {
        SysRole sysRole = MapperBeanUtils.getSysRoleMapper().selectByPrimaryKey(ao.id);
        if(null==sysRole){
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        MapperBeanUtils.getSysRoleMapper().deleteByPrimaryKey(ao.id);
    }
    public  void deleteRoleAfter() throws Exception{}

    public void deleteBatchRoleBefore() throws Exception{
        for(Long id : ao.ids){
            MapperBeanUtils.getSysRoleMapper().deleteByPrimaryKey(id);
        }
    }
    public void deleteBatchRoleAfter() throws Exception{}
}
